package com.cj.mobile.iabp.mvp.ui.activity;

import static com.cj.mobile.iabp.BuildConfig.AUTO_UPDATES;
import static com.jess.arms.utils.Preconditions.checkNotNull;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.ActivityUtils;
import com.cj.mobile.iabp.BuildConfig;
import com.cj.mobile.iabp.R;
import com.cj.mobile.iabp.app.dialog.PopupTipsDialog;
import com.cj.mobile.iabp.app.global.AccountManager;
import com.cj.mobile.iabp.app.global.Constant;
import com.cj.mobile.iabp.app.utils.AppOperator;
import com.cj.mobile.iabp.app.utils.CommonUtils;
import com.cj.mobile.iabp.app.utils.DataCleanManager;
import com.cj.mobile.iabp.di.component.DaggerSettingComponent;
import com.cj.mobile.iabp.mvp.contract.SettingContract;
import com.cj.mobile.iabp.mvp.model.entity.AppUpdate;
import com.cj.mobile.iabp.mvp.presenter.SettingPresenter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.http.imageloader.glide.ImageConfigImpl;
import com.jess.arms.utils.ArmsUtils;
import com.qiangxi.checkupdatelibrary.CheckUpdateOption;
import com.qiangxi.checkupdatelibrary.Q;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * ================================================
 * Description:设置
 * <p>
 * Created by MVPArmsTemplate on 09/15/2021 14:06
 * ================================================
 */
public class SettingActivity extends BaseActivity<SettingPresenter> implements SettingContract.View {
    /*--------------------------------控件信息--------------------------------*/
    @BindView(R.id.activity_setting)
    View myLayout;                                                                                  // 总布局

    @BindView(R.id.txvi_settingactivity_version)
    TextView txviVersion;                                                                           // 版本号

    @BindView(R.id.txvi_settingactivity_clean_cache)
    TextView txviCache;                                                                             // 缓存

    @BindView(R.id.lila_settingactivity_seturl)
    LinearLayout lilaSetUrl;                                                                        // 设置服务地址
    /*--------------------------------业务信息--------------------------------*/
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AccountManager mAccountManager;

    // 清空缓存提示
    private PopupTipsDialog mClearCacheTips = null;
    // APP升级对话框
    private MaterialDialog mDialog;
    // 已经是最新版本
    private MaterialDialog mDialogTips = null;

    /**
     * 根据主题使用不同的颜色。
     * 如果想要纯透明，则需要重写此方法，返回值为 -1 即可。
     */
    public int useStatusBarColor() {
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(android.R.color.white, typedValue, true);
        return typedValue.data;
    }

    /**
     * 将状态栏改为浅色模式(状态栏 icon 和字体会变成深色)
     */
    public boolean useLightStatusBar() {
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.txviVersion = null;
        this.txviCache = null;

        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }

        if (mDialogTips != null) {
            mDialogTips.dismiss();
            mDialogTips = null;
        }

        if (mClearCacheTips != null) {
            mClearCacheTips.dismiss();
            mClearCacheTips = null;
        }

        this.mImageLoader = null;
        this.mAccountManager = null;
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerSettingComponent
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_setting;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        // 设置标题
        setTitle("设置");

        // 初始化Loading对话框
        mDialog = new MaterialDialog.Builder(this).content("正在获取新版本信息，请稍候...").progress(true, 0).build();


        // 设置版本号
        txviVersion.setText(BuildConfig.VERSION_NAME);

        // 设置缓存
        txviCache.setText(DataCleanManager.getCacheSize(this));

        // 升级提示
        mDialogTips = new MaterialDialog.Builder(this).title("更新提示").content("已经是最新版本！").positiveText("确定").build();

        // 初始化清理缓存
        mClearCacheTips = new PopupTipsDialog(this, "是否清空缓存？", click -> {
            if (click) {
                clearAppCache(this, true);
                txviCache.setText("0KB");
            }
        });

        // 只有在测试环境才允许修改地址
        lilaSetUrl.setVisibility(BuildConfig.DEBUG ? View.VISIBLE : View.GONE);
    }

    @OnClick({
            R.id.lila_settingactivity_updatepwd,                                                    // 修改密码
            R.id.lila_settingactivity_version,                                                      // 检测更新
            R.id.lila_settingactivity_clean_cache,                                                  // 清理缓存
            R.id.lila_settingactivity_seturl,                                                       // 设置服务地址
            R.id.lila_settingactivity_about,                                                        // 关于

    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lila_settingactivity_updatepwd:                                               // 修改密码
                ActivityUtils.startActivity(ModifyLoginPwdActivity.class);
                break;
            case R.id.lila_settingactivity_version:                                                 // 检测更新
                if (AUTO_UPDATES)
                    if (!CommonUtils.isDoubleClick()) {
                        if (mPresenter != null) {
                            mPresenter.checkUpdateManager();
                        }
                    }
                break;
            case R.id.lila_settingactivity_clean_cache:                                             // 清理缓存
                if (mClearCacheTips != null)
                    mClearCacheTips.showAtLocation(v, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.lila_settingactivity_seturl:                                                  // 设置服务地址
                ActivityUtils.startActivity(SetServerAddressActivity.class);
                break;
            case R.id.lila_settingactivity_about:                                                   // 关于
                ActivityUtils.startActivity(AboutActivity.class);
                break;
        }
    }

    /**
     * 清除app缓存
     */
    public void clearAppCache(final Context context, boolean showToast) {
        final Handler handler = showToast ? new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    showMessage("缓存清除成功");
                } else {
                    showMessage("缓存清除失败");
                }
            }
        } : null;

        DataCleanManager.clearImageAllCache(context);

        AppOperator.runOnThread(() -> {
            Message msg = new Message();
            try {
                DataCleanManager.cleanApplicationData(context,
                        Constant.IMAGE_PATH,
                        Constant.CACHE_PATH,
                        Constant.APP_UPDATE_PATH,
                        Constant.VIDEO_PATH);

                msg.what = 1;
            } catch (Exception e) {
                msg.what = -1;
            }
            if (handler != null)
                handler.sendMessage(msg);
        });
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void showLoading() {
        if (mDialog != null)
            mDialog.show();
    }

    @Override
    public void hideLoading() {
        if (mDialog != null)
            mDialog.hide();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void askDialog(AppUpdate info) {
        Q.show(this, new CheckUpdateOption.Builder()
                .setAppName(info.getName())
                .setFileName("/" + info.getFileName())
                .setFilePath(Constant.APP_UPDATE_PATH)
//                .setImageUrl("http://imgsrc.baidu.com/imgad/pic/item/6c224f4a20a446233d216c4f9322720e0cf3d730.jpg")
                .setImageResId(R.mipmap.icon_upgrade_logo)
                .setIsForceUpdate(info.getForce() == 1)
                .setNewAppSize(info.getNewAppSize())
                .setNewAppUpdateDesc(info.getNewAppUpdateDesc())
                .setNewAppUrl(info.getFilePath())
                .setNewAppVersionName(info.getVerName())
                .setNotificationSuccessContent("下载成功，点击安装")
                .setNotificationFailureContent("下载失败，点击重新下载")
                .setNotificationIconResId(R.mipmap.ic_launcher)
                .setNotificationTitle(getString(R.string.app_name))
                .setMode(2)
                .build(), (view, imageUrl) -> {
            view.setScaleType(ImageView.ScaleType.FIT_XY);
            mImageLoader.loadImage(getActivity(),
                    ImageConfigImpl
                            .builder()
                            .url(imageUrl)
                            .imageView(view)
                            .build());
        });
    }

    /**
     * 已经是最新版本
     */
    @Override
    public void showLatestDialog() {
        if (mDialogTips != null) {
            mDialogTips.show();
        }
    }
}
